# -*- coding: utf-8 -*-

from flask import Flask, template_rendered
from jinja2.loaders import DictLoader
from contextlib import contextmanager

from unittest import TestCase
from google.appengine.ext import testbed
from google.appengine.api.namespace_manager import set_namespace


class TestFlask(Flask):
    """ """
    TEMPLATES = {
        'template_path': """ 
           template content
        """
    }
    def create_global_jinja_loader(self):
        """ """
        return DictLoader(self.__class__.TEMPLATES)

    
class TestFlask1(Flask):
    """ """
    def create_global_jinja_loader(self):
        """ """
        return DictLoader(self.config['TEST_TEMPLATE'])    


class TestGoogleDataStore(TestCase):
    """ """
    def setUp(self):
        """ """
        self.testbed = testbed.Testbed()
        self.testbed.activate()
        self.testbed.init_datastore_v3_stub()
        self.testbed.init_user_stub()
                
    def tearDown(self):
        self.testbed.deactivate()


class TestWithApp(TestGoogleDataStore):
    """ """
    TEMPLATES = {}
    def setUp(self):
        """ """
        super(TestWithApp, self).setUp()
        
        self.app = TestFlask1(__name__)
        self.app.config.update(
            SECRET_KEY = '12345',
            TEST_TEMPLATE = self.TEMPLATES
        )
        self.test_client = self.app.test_client()
        
        
@contextmanager
def captured_templates(app):
    recorded = []
    def record(sender, template, context, **extra):
        recorded.append((template.name, context))
    template_rendered.connect(record, app)
    try:
        yield recorded
    finally:
        template_rendered.disconnect(record, app)

        
@contextmanager      
def in_namespace(name):
    """
    Sets current namespace and removes it on exit.
    
    with in_namespace('testing'):
        ...
    """      
    set_namespace(name)
    try:
        yield
    finally:
        set_namespace('')